/*
@auther fenglei
*/
package xxdb

import (
	"errors"
	"github.com/duke-git/lancet/v2/convertor"
	"github.com/gogf/gf/v2/util/gconv"
	"gorm.io/gorm"
)

func GormError(err error) bool {
	if err == nil {
		return false
	}
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return true
	}
	return true
}
func GormToMap(v any) map[string]interface{} {
	//这个有问题，时间没有问题。 gconv.Map(obj)
	return gconv.Map(v)
}
func GormWhere(wheres map[string]map[string]interface{}) func(db *gorm.DB) *gorm.DB {
	var andWhere, orWhere, notWhere = map[string]interface{}{}, map[string]interface{}{}, map[string]interface{}{}
	var likeWhere string
	for key, value := range wheres {
		//组装where
		if key == "AND" {
			for key2, value2 := range value {
				andWhere[key2] = value2
			}
		}
		if key == "OR" {
			for key2, value2 := range value {
				orWhere[key2] = value2
			}
		}
		if key == "NOT" {
			for key2, value2 := range value {
				notWhere[key2] = value2
			}
		}
		if key == "LIKE" {
			for key2, value2 := range value {
				likeWhere += key2 + ` LIKE "` + convertor.ToString(value2) + `%" OR `
			}
			// 去除尾部OR
			likeWhere = likeWhere[:len(likeWhere)-3]
		}
	}
	return func(db *gorm.DB) *gorm.DB {
		return db.Where(andWhere).Where(likeWhere).Or(orWhere).Not(notWhere)
	}
}

// 参考 https://www.cnblogs.com/leijiangsheng/p/16533014.html
func PaginatePage(p *Pages) func(db *gorm.DB) *gorm.DB {
	return Paginate(p.Page, p.PageSize)
}

// 分页封装
func Paginate(page int, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page == 0 {
			page = 1
		}
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = DBDefaultPageSize
		}
		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
